package huizhi.net;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 文件下载
 */
public class ClientFileDownload {
    public static void main(String[] args) throws Exception{
        // 连接本机的8888端口
        Socket client = new Socket(InetAddress.getLocalHost(), 8880);
        // 从套接字获取字节输出流
        OutputStream outputStream = client.getOutputStream();
        //包装成缓冲流
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        String str = "1.jpg";
        bw.write(str);
        bw.newLine();
        bw.flush();
        //获取字节输入流
        InputStream inputStream = client.getInputStream();
        byte[] biaoji = new byte[3];
        inputStream.read(biaoji);
        //判断标记
        String s1 = new String(biaoji);
        if (s1.equals("fil")){
            System.out.println("文件存在");
            byte[] buff = new byte[1024];
            int len ;
            //获取缓冲字节输出流
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\CodeAll\\code\\ExerciseMaven\\src\\main\\java\\huizhi\\net\\2.jpg");
            while (-1 != (len= inputStream.read(buff) )){
                fileOutputStream.write(buff,0,len);
            }
        }else if(s1.equals("msg")){
            System.out.println("文件不存在");
        }else {
            System.out.println("异常");
        }
        bw.close();
        outputStream.close();
        inputStream.close();
        client.close();

    }
}
